package com.gitee.chili.leisure.server;

import com.gitee.chili.leisure.properties.InitializeNettyProperties;
import com.gitee.chili.leisure.properties.NettyHandlerProperties;
import com.gitee.chili.leisure.util.InterAddress;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.socket.SocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import io.netty.channel.ChannelInitializer;

import java.util.Objects;

/**
 * GameBootstrapServer
 *
 * @author week solider
 * @since 2020-07-21
 */

@Slf4j
@Component
public class DefaultBootstrapServer extends AbstractBootstrapServer {

    @Autowired
    public DefaultBootstrapServer(InitializeNettyProperties properties,
                                  NettyHandlerProperties handlerProperties) {

       super(properties, handlerProperties);
    }

    @Override
    protected void started() {
        bootstrap.bind(InterAddress.getHost(), properties.getPort())
                .addListener((ChannelFutureListener) channelFuture ->
                        log.info("服务端启动{} [ {} : {} ] , 目录地址: {}", channelFuture.isSuccess() ? "成功" : "失败",
                                InterAddress.getHost(), properties.getPort(), properties.getSocketPath()));
    }

    @Override
    protected void closed() {
        if (Objects.nonNull(workGroup) && Objects.nonNull(bossGroup)) {
            try {
                // 优雅关机
                bossGroup.shutdownGracefully().sync();
                workGroup.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                log.info("服务端关闭资源失败 [{} : {}]", InterAddress.getHost(), properties.getPort());
            }
        }
    }

    @Override
    protected ChannelInitializer<SocketChannel> getChannelInitializer() {
        return new DefaultChannelInitializer()
                .setInitializeNettyProperties(properties)
                .setNettyHandlerProperties(handlerProperties);
    }
}
